package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.dao.InputUserStory;
import es.udc.fic.hamNeggs.manager.ProjectManager;
import es.udc.fic.hamNeggs.manager.UserManager;
import es.udc.fic.hamNeggs.manager.UserStoriesCategoryManager;
import es.udc.fic.hamNeggs.manager.UserStoriesManager;
import es.udc.fic.hamNeggs.pojo.UserStories;
import es.udc.fic.hamNeggs.pojo.UserStories.State;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * Servlet implementation class UserStoriesManagement
 */
public class UserStoriesManagement extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(UserStoriesManagement.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserStoriesManagement() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myUser = (Long) session.getAttribute("user");

        final Long myProject = (Long) session.getAttribute("project");

        final ProjectManager prjmng = new ProjectManager();

        final HashMap<String, ArrayList<InputUserStory>> ustMap = new HashMap<String, ArrayList<InputUserStory>>();

        for (final UserStories ust : prjmng.getProject(myProject).getUserStories()) {
            final InputUserStory iust = new InputUserStory();
            iust.setUserStory(ust);
            String name = "On Backlog";
            if (ust.getSprint() != null)
                name = ust.getSprint().getName();
            ArrayList<InputUserStory> array = ustMap.get(name);
            if (array == null)
                array = new ArrayList<InputUserStory>();
            array.add(iust);
            ustMap.put(name, array);
        }

        request.setAttribute("userStories", ustMap);
        request.setAttribute("user", myUser.toString());
        request.setAttribute("rol", session.getAttribute("rol"));

        prjmng.close();

        request.getRequestDispatcher("/user_stories.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myProject = (Long) session.getAttribute("project");

        final UserStoriesManager ustmng = new UserStoriesManager();
        final UserManager usrmng = new UserManager();
        final UserStoriesCategoryManager catmng = new UserStoriesCategoryManager();
        final ProjectManager prjmgn = new ProjectManager();

        try {
            switch (request.getParameter("action")) {
                case "Add":
                case "Delete":
                    final UserStories oldStory = ustmng.getUserStories(new Long(request.getParameter("ustid")));
                    ustmng.deleteUserStories(oldStory);
                    break;
                case "StartDevelopment":
                    final String ustidsd = request.getParameter("ustid");
                    final UserStories ustsd = ustmng.getUserStories(new Long(ustidsd));
                    ustsd.setState(State.InProgress);
                    ustmng.updateUserStories(ustsd);
                    break;
                case "EndDevelopment":
                    final String ustided = request.getParameter("ustid");
                    final UserStories usted = ustmng.getUserStories(new Long(ustided));
                    usted.setRealstoryPoints(new Integer(request.getParameter("realstoryPoints")));
                    usted.setState(State.Finalized);
                    ustmng.updateUserStories(usted);
                    break;
                case "Validate":
                    final String ustidv = request.getParameter("ustid");
                    final UserStories ustv = ustmng.getUserStories(new Long(ustidv));
                    ustv.setState(State.Validated);
                    ustmng.updateUserStories(ustv);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            String error = "[";
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                final String paramName = names.nextElement();
                final String paramValue = request.getParameter(paramName);
                error = error.concat(paramName + ":" + paramValue + ";");
            }
            error = error.concat("]");
            LOG.error("Error while executing action: " + request.getParameter("action")
                    + "with params: " + error + "\n"
                    , e);
        }

        ustmng.close();
        usrmng.close();
        catmng.close();
        prjmgn.close();

        doGet(request, response);
    }

}
